package cn.jietuo.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2019-10-04
 * @description: 静态内部类
 *
 * <pre>
 *     JVM保证单例，加载外部类时不会加载内部类，这样可以实现懒加载
 * </pre>
 */
public class Singleton_InnerClass {

    private Singleton_InnerClass(){
        if (InnerClassSingletonHolder.INSTANCE != null){
            throw new RuntimeException("单例模式不能多实例");
        }
    }

    private static class InnerClassSingletonHolder {
        private static final Singleton_InnerClass INSTANCE = new Singleton_InnerClass();
    }

    public static Singleton_InnerClass getInstance(){
        return InnerClassSingletonHolder.INSTANCE;
    }


    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//        for (int i = 0; i < 10000; i++) {
//            new Thread(() -> System.out.println(Singleton_InnerClass.getInstance().hashCode())).start();
//        }
        Constructor<Singleton_InnerClass> declaredConstructor = Singleton_InnerClass.class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Singleton_InnerClass singleton_innerClass = declaredConstructor.newInstance();
        Singleton_InnerClass instance = Singleton_InnerClass.getInstance();
        System.out.println(singleton_innerClass == instance);

    }
}
